#include "input.h"
#include "core.h"

input::input()
{
	m_dinput = 0;
	m_keyboard = 0;
	m_mouse = 0;

	init();
}

input::~input()
{
	if(m_keyboard)
		m_keyboard->Unacquire();
	m_keyboard->Release();
	if(m_mouse)
		m_mouse->Unacquire();
	m_mouse->Release();

	m_dinput->Release();
}

void input::init()
{
	/*D3DCHECK(*/DirectInput8Create(GetModuleHandle(NULL),DIRECTINPUT_VERSION,IID_IDirectInput8,(void**)&m_dinput,NULL);//);
	/*D3DCHECK(*/m_dinput->CreateDevice(GUID_SysKeyboard,&m_keyboard,NULL);//);
	/*D3DCHECK(*/m_keyboard->SetDataFormat(&c_dfDIKeyboard);//);
	m_hwnd = core::get_inst().get_window()->hwnd();
	/*D3DCHECK(*/m_keyboard->SetCooperativeLevel(m_hwnd,DISCL_FOREGROUND|DISCL_NONEXCLUSIVE);//);
	/*D3DCHECK(*/m_keyboard->Acquire();//);
	/*D3DCHECK(*/m_dinput->CreateDevice(GUID_SysMouse,&m_mouse,NULL);//);
	/*D3DCHECK(*/m_mouse->SetDataFormat(&c_dfDIMouse);//);
	/*D3DCHECK(*/m_mouse->SetCooperativeLevel(m_hwnd,DISCL_FOREGROUND|DISCL_EXCLUSIVE);//);
	/*D3DCHECK(*/m_mouse->Acquire();//);

	m_mouse_pos = vector3(0.0f,0.0f,0.0f);
	m_mouse_border = vector3((float)(core::get_inst().get_window()->width()),(float)(core::get_inst().get_window()->height()),100.0f);
}

void input::update()
{
	HRESULT hr;
	u32 try_cntr=10;

	hr=m_keyboard->GetDeviceState(sizeof(BYTE)*256,&m_keys);

	if(FAILED(hr))
	{
		do{ hr=m_keyboard->Acquire(); try_cntr--; if(try_cntr<=0) return;}
		while(hr==DIERR_INPUTLOST||hr==DIERR_NOTACQUIRED);
	}

	try_cntr=10;

	hr=m_mouse->GetDeviceState(sizeof(DIMOUSESTATE),&m_mouse_state);
	if(FAILED(hr))
	{
		do{hr=m_mouse->Acquire(); try_cntr--; if(try_cntr<=0) return;}
		while(hr==DIERR_INPUTLOST||hr==DIERR_NOTACQUIRED);
	}

	m_mouse_pos.x+=m_mouse_state.lX;
	m_mouse_pos.y+=m_mouse_state.lY;
	m_mouse_pos.z+=(float)(m_mouse_state.lZ)/100.0f;

	if(m_mouse_pos.x<0)
		m_mouse_pos.x=0;
	if(m_mouse_pos.y<0)
		m_mouse_pos.y=0;
	if(m_mouse_pos.z<0)
		m_mouse_pos.z=0;

	if(m_mouse_pos.x>m_mouse_border.x)
		m_mouse_pos.x=m_mouse_border.x;
	if(m_mouse_pos.y>m_mouse_border.y)
		m_mouse_pos.y=m_mouse_border.y;
	if(m_mouse_pos.z>m_mouse_border.z)
		m_mouse_pos.z=m_mouse_border.z;
}

float input::mouse_x()
{
	return m_mouse_pos.x;
}

float input::mouse_y()
{
	return m_mouse_pos.y;
}

float input::mouse_z()
{
	return m_mouse_pos.z;
}

bool input::is_key(u8 key)
{
	if(m_keys[key]&0x80) 
		return true;
	return false;
}

bool input::is_mouse_key(u8 key)
{
	if(m_mouse_state.rgbButtons[key]&0x80) 
		return true;
	return false;
}